#include "choosefrienddialog.h"

ChooseFriendDialog::ChooseFriendDialog(QWidget *parent,const QString& userId)
    : QDialog(parent),userId(userId)
{

    this->setFixedSize(755, 550);
    //创建水平布局管理器
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setSpacing(0);
    layout->setContentsMargins(0,0,0,0);
    this->setLayout(layout);


    //初始化左右QWidget
    initLeft(layout);
    initRight(layout);

    //加载数据
    initData();

}

void ChooseFriendDialog::initLeft(QHBoxLayout* layout)
{
    //创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollArea:horizontal{height:0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical {width: 2px; background-color: rgb(255, 255, 255); } QScrollBar::handle:vertical {background-color: rgb(205, 205, 205);}");

    //实例化container
    totalContainer = new QWidget();
    totalContainer->setObjectName("totalContainer");
    totalContainer->setStyleSheet("#totalContainer {background-color: rgb(255, 255, 255);}");
    scrollArea->setWidget(totalContainer);

    //创建子布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(0);
    vlayout->setAlignment(Qt::AlignTop); // 设置靠上⽅对⻬
    totalContainer->setLayout(vlayout);


    //添加左侧全部到layout中
    layout->addWidget(scrollArea,1);

    //测试临时数据
#ifdef test
    for(int i = 1;i <= 30;i++)
    {
        addFriend(QString::number(i),QIcon(":/image/file.png"),"张三" + QString::number(i) ,false);
    }

#endif
}

void ChooseFriendDialog::initRight(QHBoxLayout* layout)
{
    //创建网格布局
    QGridLayout* glayout = new QGridLayout();
    glayout->setContentsMargins(0,0,0,0);
    glayout->setSpacing(0);
    glayout->setAlignment(Qt::AlignCenter);

    //创建文本框
    QLabel* label = new QLabel();
    label->setText("选择联系人");
    label->setFixedHeight(30);
    label->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);
    label->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    label->setStyleSheet("QLabel { font-size:16px; font-weight: 700; }");

    //创建滚动区域
    QScrollArea* scrollArea = new QScrollArea();
    scrollArea->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->horizontalScrollBar()->setStyleSheet("QScrollArea:horizontal{height:0px;}");
    scrollArea->verticalScrollBar()->setStyleSheet("QScrollBar:vertical {width: 2px; background-color: rgb(255, 255, 255); } QScrollBar::handle:vertical {background-color: rgb(205, 205, 205);}");

    //实例化container
    selectedContainer = new QWidget();
    selectedContainer->setObjectName("selectedContainer");
    selectedContainer->setStyleSheet("#selectedContainer {background-color: rgb(255, 255, 255);}");
    scrollArea->setWidget(selectedContainer);

    //创建子布局管理器
    QVBoxLayout* vlayout = new QVBoxLayout();
    vlayout->setContentsMargins(0, 0, 0, 0);
    vlayout->setSpacing(0);
    vlayout->setAlignment(Qt::AlignTop); // 设置靠上⽅对⻬
    selectedContainer->setLayout(vlayout);

    //创建底部按钮
    QPushButton* yesBtn = new QPushButton();
    QPushButton* noBtn = new QPushButton();

    yesBtn->setFixedSize(110,30);
    noBtn->setFixedSize(110,30);

    yesBtn->setText("确定");
    noBtn->setText("取消");

    yesBtn->setStyleSheet("QPushButton{background-color:rgb(7, 193, 96);} QPushButton:hover {background-color:rgb(56, 205, 127;}");
    noBtn->setStyleSheet("QPushButton{background-color:rgb(243, 243, 243);} QPushButton:hover {background-color:rgb(219, 219, 219;}");

    //添加组件到布局管理器中,共分为9列, 底部按钮占3列, 空白控件占1列
    glayout->addWidget(label,0,0,1,9);
    glayout->addWidget(scrollArea,1,0,1,9);
    glayout->addWidget(yesBtn,2,1,1,3);
    glayout->addWidget(noBtn,2,5,1,3);

    layout->addLayout(glayout,1);

    ///////////////////////////////////////////////
    /// 关联确定与取消按钮
    //////////////////////////////////////////////
    connect(yesBtn,&QPushButton::clicked,this,&ChooseFriendDialog::clickYesBtn);
    connect(noBtn,&QPushButton::clicked,this,[=](){
        this->close();
    });
}

void ChooseFriendDialog::clickYesBtn()
{
    QList<QString> list = generateMemberList();

    if(list.count() < 3)
    {
        Toast::showMessage("创建群聊至少需要三个好友!");
        return;
    }
    else
    {
        model::DataCenter* dataCenter = model::DataCenter::getInstance();
        dataCenter->createGroupChatSessionAsync(list);
        this->close();
    }
}

QList<QString> ChooseFriendDialog::generateMemberList()
{
    QList<QString> ret;

    //首先添加自身
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    ret.push_back(dataCenter->getMyself()->userId);

    //此次, 添加右侧好友
    QVBoxLayout* vlayout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());

    for(int i = vlayout->count() - 1; i >= 0;--i)
    {
        auto item = vlayout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr) continue;

        ret.push_back(dynamic_cast<ChooseFriendItem*>(item->widget())->userId);
    }

    return ret;
}

void ChooseFriendDialog::initData()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    auto friendList = dataCenter->getFriendList();
    if(friendList == nullptr || friendList->isEmpty())
    {
        LOG() << "ChooseFriendDialog::initData() 失败, 原因: 好友列表为空";
        return;
    }

    for(auto& f : *friendList)
    {
        if(f.userId == userId)
        {
            addFriend(f.userId,f.userIcon,f.userName,true);
            addSelectedFriend(f.userId,f.userIcon,f.userName);
        }
        else
            addFriend(f.userId,f.userIcon,f.userName,false);
    }
}



void ChooseFriendDialog::addFriend(const QString &userId, const QIcon& avatar, const QString &name, bool checked)
{
    ChooseFriendItem* item = new ChooseFriendItem(this,userId,avatar,name,checked);
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(totalContainer->layout());
    layout->addWidget(item);
}

void ChooseFriendDialog::addSelectedFriend(const QString &userId, const QIcon& avatar, const QString &name)
{
    ChooseFriendItem* item = new ChooseFriendItem(this,userId,avatar,name,true);
    QVBoxLayout* layout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    layout->addWidget(item);
}

void ChooseFriendDialog::deleteSelectedFriend(const QString &userId)
{
    /////////////////////////////////
    ///右侧删除逻辑
    /// /////////////////////////////

    QVBoxLayout* rlayout = dynamic_cast<QVBoxLayout*>(selectedContainer->layout());
    //由于是遍历 + 删除, 所以需要从后往前遍历
    for(int i = rlayout->count()-1;i>=0;i--)
    {
        auto* item = rlayout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr) continue;
        if(dynamic_cast<ChooseFriendItem*>(item->widget())->userId != userId) continue;

        //匹配成功,执行删除逻辑
        rlayout->removeItem(item);
        item->widget()->deleteLater();
    }
    /////////////////////////////////
    ///左侧更改逻辑
    /// /////////////////////////////
    QVBoxLayout* llayout = dynamic_cast<QVBoxLayout*>(totalContainer->layout());
    //由于是遍历 + 删除, 所以需要从后往前遍历
    for(int i = llayout->count()-1;i>=0;i--)
    {
        auto* item = llayout->itemAt(i);
        if(item == nullptr || item->widget() == nullptr) continue;
        if(dynamic_cast<ChooseFriendItem*>(item->widget())->userId != userId) continue;

        //匹配成功,执行修改逻辑
        dynamic_cast<ChooseFriendItem*>(item->widget())->checkBox->setChecked(false);
    }
}

ChooseFriendItem::ChooseFriendItem(ChooseFriendDialog *owner, const QString &userId, const QIcon& avatar, const QString &name, bool checked = false)
    :owner(owner), userId(userId),avatar(avatar), name(name)
{
    //设置基本属性
    this->setFixedHeight(50);
    this->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Fixed);

    //创建水平布局管理器
    QHBoxLayout* layout = new QHBoxLayout();
    layout->setSpacing(10);
    layout->setContentsMargins(10,5,10,5);
    this->setLayout(layout);

    //创建头像
    QPushButton* avatarBtn = new QPushButton();
    avatarBtn->setFixedSize(30,30);
    avatarBtn->setIconSize(QSize(30,30));
    avatarBtn->setIcon(avatar);

    //创建昵称文本
    QLabel* nameLabel = new QLabel();
    nameLabel->setText(name);
    nameLabel->setAlignment(Qt::AlignLeft | Qt:: AlignVCenter);

    //创建复选框
    checkBox = new QCheckBox();
    checkBox->setFixedSize(20,20);
    checkBox->setChecked(checked);
    checkBox->setStyleSheet("QCheckBox::indicator { width: 20px; height:20px;image: url(:/image/unchecked.png); } QCheckBox::indicator:checked { image:url(:/image/checked.png); }");

    connect(checkBox, &QCheckBox::toggled, this,&ChooseFriendItem::toggleCheckBox);


    // 添加到布局管理器中
    layout->addWidget(checkBox);
    layout->addWidget(avatarBtn);
    layout->addWidget(nameLabel);
}

void ChooseFriendItem::toggleCheckBox(bool checked)
{
    LOG() << "ChooseFriendItem::toggleCheckBox(bool checked)";

    if(checked)
    {
        owner->addSelectedFriend(userId, avatar, name);
        LOG() << "owner->addSelectedFriend(userId, avatar, name);";
    }
    else
    {
        owner->deleteSelectedFriend(userId);
        LOG() << "owner->deleteSelectedFriend(userId);";
    }
}
